package cn.org.spring.wechar.service;

import cn.org.spring.common.util.HttpClientUtils;
import cn.org.spring.wechar.bean.Button;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 自定义菜单service服务
 * Created with IntelliJ IDEA.
 * User:  wanghongjie
 * Date:  2020/10/14 - 21:06
 * <p>
 * Description:
 */
@Service
public class MenuService {

    private static final String CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    private static final String DELETE_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

    @Autowired
    private AccessTokenService accessTokenService;

    public void createMenu(String json) throws IOException {
        sendPost(json);
    }

    /**
     * 创建菜单
     *
     * @param button
     * @throws IOException
     */
    public void createMenu(Button button) throws IOException {
        String s = sendPost(button.toJson());
        System.out.println(s);
    }

    /**
     * 删除菜单
     *
     * @throws IOException
     */
    public void deleteMenu() throws IOException {
        HttpClientUtils.get(DELETE_URL.replace("ACCESS_TOKEN", accessTokenService.getAccessToken()));
    }

    /**
     * 发送POST请求
     *
     * @param data 请求数据
     * @return
     * @throws IOException
     */
    private String sendPost(String data) throws IOException {
        return HttpClientUtils.post(CREATE_URL.replace("ACCESS_TOKEN", accessTokenService.getAccessToken()), data);
    }
}